package com.example.pre.business.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import com.example.pre.business.AskOffBusiness;
import com.example.pre.enums.AskOffTypeEnum;
import com.example.pre.enums.BusinessStatusEnum;
import com.example.pre.exception.ServiceException;
import com.example.pre.model.AskOff;
import com.example.pre.service.AskOffService;
import com.example.pre.tools.StringUtils;

/**
 * 请假申请业务层实现类
 * 
 * @author Administrator
 *
 */
@Controller
@Transactional(rollbackFor = Exception.class)
public class AskOffBusinessImpl implements AskOffBusiness {

	@Autowired
	private AskOffService askOffService;

	@Override
	public AskOff createAskOff(int userId, Long startTime, Long endTime, int duration, AskOffTypeEnum type,
			String content, MultipartFile file) throws Exception {
		// 附件存放目录
		String path = ResourceUtils.getURL("classpath:static/").getPath();
		String fileName = file.getOriginalFilename();
		String fileUUID = path + fileName;
		System.out.println(fileUUID + "==============");
		File newFile = new File(path, fileName);
		if (!newFile.getParentFile().exists()) {
			newFile.getParentFile().mkdir();
		}
		file.transferTo(newFile);
		AskOff askOff = new AskOff();
		askOff.setContent(content);
		askOff.setCreateTime(System.currentTimeMillis());
		askOff.setCreateUserId(userId);
		askOff.setDuration(duration);
		askOff.setEndTime(endTime);
		askOff.setFileUUID(fileUUID);
		askOff.setStartTime(startTime);
		askOff.setStatus(BusinessStatusEnum.editing.name());
		askOff.setType(type.name());
		askOff.setUpdateTime(System.currentTimeMillis());
		askOff.setUpdateUserId(userId);
		askOffService.create(askOff);
		return askOff;
	}

	@Override
	public void updateAskOff(int userId, int askOffId, Long startTime, Long endTime, Integer duration,
			AskOffTypeEnum type, String content, MultipartFile file) throws Exception {

		AskOff askOff = askOffService.get(askOffId);
		if (askOff == null) {
			throw new ServiceException("请假申请不存在id=" + askOffId, "请假申请不存在", -404);
		}
		int flag = 0;
		if (startTime != null && startTime != askOff.getStartTime()) {
			askOff.setStartTime(startTime);
			flag++;
		}
		if (endTime != null && endTime != askOff.getEndTime()) {
			askOff.setEndTime(endTime);
			flag++;
		}
		if (endTime != null && endTime != askOff.getEndTime()) {
			askOff.setEndTime(endTime);
			flag++;
		}
		if (duration != null && duration != askOff.getDuration()) {
			askOff.setDuration(duration);
			flag++;
		}
		if (type != null && type.name() != askOff.getType()) {
			askOff.setType(type.name());
			flag++;
		}
		if (StringUtils.isNotEmpty(content) && content != askOff.getContent()) {
			askOff.setContent(content);
			flag++;
		}
		if (file != null) {
			String path = ResourceUtils.getURL("classpath:static/").getPath();
			String fileName = file.getOriginalFilename();
			String fileUUID = path + fileName;
			File newFile = new File(path, fileName);
			if (!newFile.getParentFile().exists()) {
				newFile.getParentFile().mkdir();
			}
			file.transferTo(newFile);
			askOff.setFileUUID(fileUUID);
			flag++;
		}
		if (flag > 0) {
			askOff.setUpdateUserId(userId);
			askOff.setUpdateTime(System.currentTimeMillis());
			askOffService.update(askOff);
		}

	}

	@Override
	public AskOff checkAskOff(int askOffId) throws Exception {
		return askOffService.get(askOffId);
	}

	@Override
	public Map<String, Object> flowAskOff(Integer askOffId) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void downAskOff(HttpServletRequest request, HttpServletResponse response, int askOffId) throws Exception {
		AskOff askOff = askOffService.get(askOffId);
		if (askOff == null) {
			throw new ServiceException("请假申请不存在id=" + askOffId, "请假申请不存在", -404);
		}
		File file = new File(askOff.getFileUUID());
		// 取得文件名。
		String filename = file.getName();

		// 以流的形式下载文件。
		InputStream fis = new BufferedInputStream(new FileInputStream(askOff.getFileUUID()));
		byte[] buffer = new byte[fis.available()];
		fis.read(buffer);
		fis.close();
		// 清空respons
		response.reset();
		// 设置response的Header
		response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
		response.addHeader("Content-Length", "" + file.length());
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/octet-stream");
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
	}

}
